import { ref, computed, nextTick } from "vue";

export default function useEditTodo(todosRef) {
	const editingTodoRef = ref(null);
	const EditInputMap = {};
	let cachaTitle = null;

	// 获取每个editInput的element
	const setEditInputRef = (el, key) => {
		if (el) {
			EditInputMap[key] = el;
		}
	};

	// 选中编辑的todo
	const editTodo = (todo) => {
		cachaTitle = todo.title;
		editingTodoRef.value = todo;
		if (todo) {
			nextTick(() => {
				EditInputMap[`editInput${todo.id}`].focus();
			});
		}
	};

	// 完成编辑
	const doneEdit = (todo) => {
		editingTodoRef.value = null;
		const title = todo.title.trim();
		if (title) {
			todo.title = title;
		} else {
			const index = todosRef.value.indexOf(todo);
			if (index >= 0) {
				todosRef.value.splice(index, 1);
			}
		}
	};

	// 取消编辑
	const cancelEdit = (todo) => {
		editingTodoRef.value = null;
		todo.title = cachaTitle;
	};

	// 当全部勾选时的状态
	const allDoneRef = computed(() => {
		return todosRef.value.every((todo) => todo.completed);
	});

	// 当选中全选框的操作
	const setAllChecked = (checkd) => {
		todosRef.value.forEach((todo) => {
			todo.completed = checkd;
		});
	};

	return {
		editingTodoRef,
		editTodo,
		setEditInputRef,
		doneEdit,
		cancelEdit,
		allDoneRef,
		setAllChecked
	};
}
